﻿using System;
using System.Linq;
using UnityEngine;

namespace JH
{
    public static class GetGoBounds
    {
        /// <summary>
        /// 获取模型边界
        /// </summary>
        public static Bounds GetBoundsEm(this GameObject go, bool includeInactive = false)
        {
            var renders = go.GetComponentsInChildren<Renderer>(includeInactive);
            if (renders == null || renders.Length == 0) return default;
            var bounds = renders.First().bounds;
            foreach (var eachRender in renders)
            {
                bounds.Encapsulate(eachRender.bounds);
            }

            return bounds;
        }

        /// <summary>
        ///  获取边界的8个角
        /// </summary>
        public static Vector3[] GetBoundsCornersEm(this Bounds bounds)
        {
            var corners = new Vector3[8];
            var min = bounds.min;
            var max = bounds.max;
            corners[0] = new Vector3(min.x, min.y, min.z); //小 小 小
            corners[1] = new Vector3(min.x, max.y, min.z); //小 大 小
            corners[2] = new Vector3(max.x, max.y, min.z); //大 大 小
            corners[3] = new Vector3(max.x, min.y, min.z); //大 小 小
            corners[4] = new Vector3(min.x, min.y, max.z); //小 小 大
            corners[5] = new Vector3(min.x, max.y, max.z); //小 大 大
            corners[6] = new Vector3(max.x, max.y, max.z); //大 大 大
            corners[7] = new Vector3(max.x, min.y, max.z); //大 小 大
            return corners;
        }

        /// <summary>
        ///  获取边界的屏幕空间范围
        /// </summary>
        /// <returns> 返回左下角 右下角 左上角 右上角</returns>>
        public static Vector2[] GetBoundsCornersInScreenEm(this Bounds bounds, Camera camera)
        {
            //初始化相机
            if (camera == null) throw new ArgumentNullException(nameof(camera), "相机为空！");

            //获取世界坐标边界
            var worldCorners = GetBoundsCornersEm(bounds);

            //转换为屏幕坐标
            var screenCorners = new Vector2[8];
            for (int i = 0; i < 8; i++)
            {
                screenCorners[i] = camera.WorldToScreenPoint(worldCorners[i]);
            }

            //找到最小最大值
            var xMin = screenCorners.Min(v => v.x);
            var xMax = screenCorners.Max(v => v.x);
            var yMin = screenCorners.Min(v => v.y);
            var yMax = screenCorners.Max(v => v.y);

            //返回左下角 右下角 左上角 右上角
            return new[]
            {
                new Vector2(xMin, yMin),
                new Vector2(xMin, yMax),
                new Vector2(xMax, yMin),
                new Vector2(xMax, yMax)
            };
        }
    }
}